package com.cloudbroker.bcs.common.util;

import org.apache.commons.lang3.StringUtils;

import com.cloudbroker.bcs.common.cache.CacheClient;

public abstract class CacheHelper {
    
    public abstract CacheClient getCacheClient();
    
    public void set(String key, String value, int expireSecs) {
        if (0 > expireSecs) {
            getCacheClient().set(key, value);
        } else {
            getCacheClient().set(key, value, expireSecs);
        }
    }

    public void delete(String key) {
        getCacheClient().delete(key);
    }
    
    public String get(String key) {
        // 空白key直接返回null
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return getCacheClient().get(key);
    }
    
    public boolean exists(String key) {
        return getCacheClient().exists(key);
    }
    
    public boolean refresh(String key, int expireSecs) {
        if (0 > expireSecs) {
            return getCacheClient().persist(key);
        } else {
            return getCacheClient().expire(key, expireSecs);
        }
    }
    
    public void destroy(String key) {
        getCacheClient().delete(key);
    }
    
    public boolean check(String key, String value) {
        String valueSaved = getCacheClient().get(key);
        return null != valueSaved && valueSaved.equals(value);
    }

    public void update(String key,String value){
        Long expireSecs = getCacheClient().ttl(key);
        getCacheClient().set(key, value, expireSecs.intValue());
    }


}
